import bpy
import time
from bpy.types import Operator
from os.path import split, join
from ....addon.paths import FluidLabPreferences


class FLUIDLAB_OT_flipbook(Operator):
    bl_idname = "fluidlab.flipbook"
    bl_label = "Vista previa del Flipbook"
    bl_description = "Vista previa del renderizado Flipbook"
    bl_options = {'REGISTER', 'UNDO'}


    def set_flipbook_output(self, preferences):
        flipbook_output_path = preferences.flipbooks_path
        if not flipbook_output_path:
            self.report({'ERROR'}, "Please set Flipbook Output in preferences!")
            return {'CANCELLED'}
        return flipbook_output_path


    def set_render_settings(self, context, preferences):
        # Configuración de la escena de renderizado
        flipbook_without_overlays = preferences.flipbook_without_overlays
        context.scene.render.filepath = self.get_final_path(context, preferences)
        if flipbook_without_overlays:
            context.space_data.overlay.show_overlays = False

    def get_final_path(self, context, preferences):
        
        blend_file = (split(bpy.data.filepath)[-1].split(".")[0]) or ("Unsaved_Scene" + "_" + time.strftime("%dd_%Hh_%Mm_%Ss"))
        formatos_video = {'AVI_JPEG', 'AVI_RAW', 'FFMPEG'}
        subfolders_enabled = preferences.use_flipbooks_in_subfolders
        only_for_img_sequences = preferences.only_for_img_sequences
        file_format_is_video = context.scene.render.image_settings.file_format in formatos_video
            
        subfolder_path = blend_file if subfolders_enabled and (not only_for_img_sequences or not file_format_is_video) else ""

        return join(preferences.flipbooks_path, subfolder_path, blend_file + "_")


    def invoke_opengl_render(self):
        bpy.ops.render.opengl('INVOKE_DEFAULT', animation=True)
    

    def execute(self, context):
        preferences = FluidLabPreferences.get_prefs(context)

        flipbook_output_path = self.set_flipbook_output(preferences)
        if 'CANCELLED' in flipbook_output_path:
            return {'CANCELLED'}

        self.set_render_settings(context, preferences)
        self.invoke_opengl_render()

        return {'FINISHED'}